<script setup lang="ts">
import type { FormInst } from 'naive-ui'
import { useCountDown } from '../composables'
import PreivewEnterInfo from './preivew-enter-info.vue'
import { getSubmitWorkById, submitWork } from '~/api'
import type { SubmitWork, SubmitWorkInfo } from '~/api'
import { validateImg, validatePDF, validateVideo } from '~/utils/misc'

const props = defineProps({
  isOpenType: String as PropType<'perview' | 'add' | 'edit' | 'submit'>,
  isWorkId: String,
})

const emit = defineEmits<{
  (e: 'submit'): void
}>()

const previewComp = ref<InstanceType< typeof PreivewEnterInfo>>()

const showModal = ref(false)

const store = useTeamInfoStore()

const { userInfo, basicInfo } = storeToRefs(store)

const formData = ref<SubmitWork>({
  id: '',
  scheduleId: basicInfo.value?.scheduleId ?? '',
  userId: userInfo.value?.userId,
  operateType: 'TEMPORARY_STORAGE',
  worksName: '',
  /** 是否作品组图(0，是1，否 */
  isGroupImg: '',
  /** 作品简介 */
  worksIntro: '',
  /** "创意理念 */
  worksOriginality: '',
  /** "研究内容 */
  studyContent: '',
  /** 参赛作品高清图，逗号隔 */
  worksImg: '',
  /** 作品主图 */
  worksImgMain: '',
  /** 承诺书附件ID */
  promise: '',
  /** 作品视频附件ID */
  worksVideo: '',
  /** 验证码 */
  code: '1',
  isPc: true,
})

const worksImg = ref<string[]>([])
const promise = ref<string>('')
const worksVideo = ref<string[]>([])

const form = ref<FormInst | null>()

const message = useMessage()

const workInfo = ref<SubmitWorkInfo>()

const worksVideoList = computed(() => {
  return workInfo.value?.worksVideoVo?.map(d => ({
    ...d,
    // fileUrl: ''
  })) ?? []
})

const uploadFileFinished = ref<Record<string, boolean>>({})

const { runAsync, loading } = useRequest(submitWork, {
  manual: true,
  onSuccess(_, params) {
    message.success(`${params[0].operateType === 'SUBMIT' ? '提交' : '暂存'}成功`)
    emit('submit')
  },
})

async function hanldeSubmit(operateType: SubmitWork['operateType'] = 'TEMPORARY_STORAGE', code = '1') {
  await validateUpload()
  return form.value?.validate().then((res) => {
    return runAsync({ ...formData.value, operateType, isPc: operateType === 'SUBMIT', code })
  }, () => {
    message.error('作品信息不完整，请检查')
  })
}

const countDown = useCountDown()

async function handleConfirm() {
  // dialog.create({
  //   type: 'success',
  //   title: '确认提交',
  //   content: '提交后无法修改，确认提交吗？',
  //   positiveText: '确认',
  //   negativeText: '取消',
  //   onPositiveClick() {
  //     hanldeSubmit('SUBMIT')
  //   },
  // })

  await validateUpload()

  return form.value?.validate().then((res) => {
    showModal.value = true
    countDown.start()
  }, () => {
    message.error('作品信息不完整，请检查')
  })
}

// async function sendCode() {
//   getWorksCode().then((res) => {
//     showCodeTime.value = true

//     const timer = setInterval(() => {
//       codeTime.value -= 1
//       if (codeTime.value <= 0) {
//         codeTime.value = 60
//         showCodeTime.value = false
//         clearInterval(timer)
//       }
//     }, 1000)
//   })
// }

const { loading: dataLoading } = useRequest(getSubmitWorkById, {
  manual: !(props.isOpenType !== 'add' && props.isWorkId),
  defaultParams: [props!.isWorkId ?? ''],
  onSuccess(res) {
    const data = res.data
    workInfo.value = { ...res.data }

    formData.value = {
      ...formData.value,
      id: data.id,
      scheduleId: basicInfo.value?.scheduleId,
      userId: userInfo.value?.userId,
      operateType: data.operateType,
      worksName: data.worksName,
      /** 是否作品组图(0，是1，否 */
      isGroupImg: `${data.isGroupImg}`,
      /** 作品简介 */
      worksIntro: data.worksIntro,
      /** "创意理念 */
      worksOriginality: data.worksOriginality,
      /** "研究内容 */
      studyContent: data.studyContent,
      /** 参赛作品高清图，逗号隔 */
      worksImg: data.worksImg,
      /** 作品主图 */
      worksImgMain: data.worksImgMain,
      /** 承诺书附件ID */
      promise: data.promise,
      /** 作品视频附件ID */
      worksVideo: data.worksVideoVo?.map(d => d.id).join(',') ?? '',
      /** 验证码 */
      code: '',
    }

    worksImg.value = data.worksImg?.split(',') ?? []
    promise.value = data.promise
    worksVideo.value = data.worksVideoVo?.map(d => d.id) ?? []
  },

})

// if (props.isOpenType !== 'add' && props.isWorkId) {
//   getSubmitWorkById(props.isWorkId).then((res) => {

//   })
// }

const router = useRouter()
function handleEditEnterInfo() {
  hanldeSubmit()?.finally(() => {
    router.push('/user/enter')
  })
}
function hanldeSubmitWork() {
  previewComp.value?.validate().then((res: any) => {
    hanldeSubmit('SUBMIT', res.code)?.then(() => {
      showModal.value = false
    })
  }, () => {
    message.error('请输入验证码')
  })
}

function onUpdating(key: string, finished = false) {
  uploadFileFinished.value[key] = finished
}

async function validateUpload() {
  const flag = Object.values(uploadFileFinished.value).every(d => d)
  if (!flag) {
    message.error('请等待上传完成后提交')
    return Promise.reject(new Error('请等待上传完成后提交'))
  }

  return flag
}
</script>

<template>
  <n-spin :show="dataLoading">
    <n-scrollbar style="height: 60vh">
      <n-form ref="form" :model="formData" :disabled="isOpenType === 'perview'">
        <n-grid>
          <n-form-item-gi path="worksName" span="24" label="参赛作品名称" :label-style="{ fontWeight: 500 }" :rule="[{ trigger: 'blur', required: true, message: '请输入参赛作品名称' }]">
            <n-input v-model:value="formData.worksName" placeholder="请输入作品名称" maxlength="100" />
          </n-form-item-gi>
          <n-form-item-gi path="isGroupImg" span="24" label="是否为系列组图" :label-style="{ fontWeight: 500 }" :rule="[{ trigger: ['blur', 'change'], required: true, message: '请选择是否为系列组图' }]">
            <n-select
              v-model:value="formData.isGroupImg" placeholder="请选择" :options="[{
                label: '是', value: '0',
              }, {
                label: '否', value: '1',
              }]"
            />
          </n-form-item-gi>
          <n-form-item-gi
            path="worksIntro" span="24" label="作品简介" :label-style="{ fontWeight: 500 }"
            :rule="[{ trigger: 'blur', required: true, message: '请输入作品简介' }]"
          >
            <n-input v-model:value="formData.worksIntro" maxlength="150" show-count placeholder="请客观简要介绍作品的创意是什么，用什么细菌通过什么方法创作而成，100字以内。" type="textarea" />
          </n-form-item-gi>
          <n-grid-item span="24">
            <div text="3" mb-4>
              参考模板：该作品秉承“国以农为本，人以食为天”的理念，依据华中农大百年学府勤扎耕，肩负重任再出发为创意原点进行构思。经过悉心设计，以灭
              菌细毛笔、粗端牙签为画笔，以粘质沙雷氏菌、大肠杆菌和金黄色葡萄球菌等偏暖色调菌种为颜料，在特制调色、渐变渲染的LB培养基上逐步创作而成。
            </div>
          </n-grid-item>
          <n-form-item-gi
            path="worksOriginality" span="24" label="创意理念" :label-style="{ fontWeight: 500 }"
            :rule="[{ trigger: 'blur', required: true, message: '请输入创意理念' }]"
          >
            <n-input v-model:value="formData.worksOriginality" placeholder="请详细介绍作品的创意理念" type="textarea" />
          </n-form-item-gi>
          <n-form-item-gi
            path="studyContent" span="24" label="研究内容" :label-style="{ fontWeight: 500 }"
            :rule="[{ trigger: 'blur', required: true, message: '请输入研究内容' }]"
          >
            <n-input v-model:value="formData.studyContent" placeholder="请介绍参赛作品的研究目的、研究方法、研究过程、研究结果、研究总结等" type="textarea" />
          </n-form-item-gi>
          <n-form-item-gi path="worksImg" span="24" label="请提交高清作品图" :label-style="{ fontWeight: 500 }" :show-require-mark="true">
            <app-upload
              list-type="image-card"
              :validate-file="validateImg"
              :file-list="workInfo?.worksImgList"
              accept=".jpg,.jpeg" :max="5"
              @updateFiles="worksImg = $event; formData.worksImg = worksImg.join(',')"
              @updating="onUpdating('img')"
              @finally="onUpdating('img', true)"
            />
          </n-form-item-gi>
          <n-form-item-gi path="" span="24">
            <div text="3">
              注：图片尺寸不低于1024*768px，分辨率72dpi，格式为JPG，不低于1M，不高于50M，建议作品图背景为黑色。系列组图最多上传5张，若该作品为非系列组图，且上传数量多于一张，则以第一张为正式参赛作品图。
            </div>
          </n-form-item-gi>
          <n-form-item-gi path="worksVideo" span="24" label="请提交作品创作过程短视频" :label-style="{ fontWeight: 500 }" :show-require-mark="true">
            <app-upload
              :file-list="worksVideoList" :validate-file="validateVideo" accept=".mp4" :max="1" @updateFiles="worksVideo = $event; formData.worksVideo = worksVideo.join(',')"
              @updating="onUpdating('video')"
              @finally="onUpdating('video', true)"
            />
          </n-form-item-gi>
          <n-form-item-gi path="" span="24">
            <div text="3">
              注：最多1个文件，每个300M以内，视频时长1min以内，格式为MP4
            </div>
          </n-form-item-gi>
          <n-form-item-gi path="promise" span="24" label="请上传原创承诺书" :label-style="{ fontWeight: 500 }" :show-require-mark="true">
            <app-upload
              :file-list="workInfo?.promiseVo ? [workInfo?.promiseVo] : []" :validate-file="validatePDF" accept=".pdf" :max="1" @updateFiles="promise = $event?.[0]; formData.promise = promise"
              @updating="onUpdating('file')"
              @finally="onUpdating('file', true)"
            />
          </n-form-item-gi>
          <n-form-item-gi path="" span="24">
            <div text="3">
              注：最多1个文件，每个50M以内，手写签字后扫描为PDF进行上传
            </div>
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </n-scrollbar>
    <n-space justify="center">
      <!-- <div w="40"> -->
      <n-button v-show="isOpenType === 'add'" :loading="loading" :ghost="isOpenType !== 'submit'" type="primary" class="" @click="hanldeSubmit()">
        暂存
      </n-button>
      <n-button v-show="isOpenType === 'edit'" :loading="loading" :ghost="isOpenType !== 'submit'" type="primary" class="" @click="hanldeSubmit()">
        保存修改
      </n-button>

      <n-button v-show="isOpenType === 'add' || isOpenType === 'edit' || isOpenType === 'submit'" :loading="loading" type="primary" class="" @click="handleConfirm">
        提交
      </n-button>
      <!-- </div> -->
      <!-- <div w="40">
        <n-button ghost block type="primary">
          暂存
        </n-button>
      </div> -->
    </n-space>
  </n-spin>

  <n-modal v-model:show="showModal" closable :mask-closable="false" @close="countDown.stop()">
    <n-card
      style="width: 80vw;  overflow: hidden;"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
      closable
      @close="showModal = false"
    >
      <template #header>
        <div text="center">
          确认团队信息
        </div>
      </template>
      <div class="h-70vh">
        <PreivewEnterInfo ref="previewComp" :disabled="!countDown.isZero.value" />
      </div>
      <template #footer>
        <n-space align="center" justify="center" w-full>
          <n-button type="primary" ghost @click="handleEditEnterInfo">
            修改信息
          </n-button>
          <n-button type="primary" :disabled="!countDown.isZero.value" :loading="loading" @click="hanldeSubmitWork">
            我已确认，提交作品 {{ countDown.isZero.value ? '' : `(${countDown.count.value})` }}
          </n-button>
        </n-space>
      </template>
    </n-card>
  </n-modal>
</template>

<style scoped>

</style>
